package com.itheima.mp.service.impl;

import com.itheima.mp.domain.ResponseResult;
import com.itheima.mp.domain.dto.LoginUserDto;
import com.itheima.mp.domain.po.LoginUser;
import com.itheima.mp.domain.po.SgUser;
import com.itheima.mp.service.ILoginService;
import com.itheima.mp.utils.JwtUtil;
import com.itheima.mp.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LoginService implements ILoginService {

    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;
    @Override
    public ResponseResult login(LoginUserDto loginUser) {
        // 获取AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果失败，返回错误信息
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名/密码错误");
        }
        // 如果认证成功，获取其userId，生成jwt token
        LoginUser user = (LoginUser) authenticate.getPrincipal();
        Long userId = user.getUser().getId();
        String jwt = JwtUtil.createJWT(userId.toString());
        // 把完整的用户信息存入redis，userid作为key
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        redisCache.setCacheObject("login:" + userId, user);
        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除redis中的用户信息
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200, "注销成功");
    }
}
